﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.Shapes;
using System.Drawing;
using Silvermoon.OpenGL.Native;

namespace Silvermoon.Shapes
{
    /// <summary>
    /// Shape that renders a single colored rectangle.
    /// </summary>
    public class RectangleShape : ColorShape
    {
        private uint bufferName;

        public RectangleShape()
            : base()
        {
        }

        public RectangleShape(Color c)
            : base(c)
        {
        }

        public override void Dispose()
        {
            if (bufferName != 0) gl.DeleteBuffer(bufferName);
            bufferName = 0;

            base.Dispose();
        }


        protected override Color GetShapeColor()
        {
            return Color;
        }


        protected override void Layout()
        {
            if (bufferName == 0) bufferName = gl.GenBuffer();

            Size r = Size;
            short right = (short)(r.Width);
            short bottom = (short)(r.Height);

            short[] rectangleVertex = new short[] 
                    { 
                        right, bottom,
                        right, 0,
                        0, bottom,
                        0, 0 
                    };

            BufferTarget bt = BufferTarget.ArrayBuffer;
            gl.BindBuffer(bt, bufferName);
            gl.BufferData(bt, sizeof(short) * rectangleVertex.Length, rectangleVertex, BufferUsage.StaticDraw);
            gl.BindBuffer(bt, 0);
            base.Layout();
        }

        public override void Render(Silvermoon.Core.Renderer renderer)
        {
            if (Color.IsEmpty) return;
            Color c = GetShapeColor();
            gl.Color4x(c.R << 8, c.G << 8, c.B << 8, c.A * renderer.Alpha);
            gl.DisableClientState(ClientStateArray.TextureCoord);
            gl.Disable(Capability.Texture2D);
            gl.BindBuffer(BufferTarget.ArrayBuffer, bufferName);
            gl.VertexPointer(2, glValueType.Short, 0, IntPtr.Zero);
            //gl.VertexPointer(2, glValueType.Short, 0, rectangleVertex);
            gl.DrawArrays(PrimitiveType.TriangleStrip, 0, 4);
            gl.EnableClientState(ClientStateArray.TextureCoord);
            gl.Enable(Capability.Texture2D);
            gl.BindBuffer(BufferTarget.ArrayBuffer, 0);
        }

        protected override Shape CreateClone()
        {
            return new RectangleShape();
        }
    }
}
